#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
#include<map>
#include<math.h>
using namespace std;


class Solution {
public:
    int getNumberOfBacklogOrders(vector<vector<int>>& orders) {
        map<int,int> sellMap;
        map<int,int,greater<int>> buyMap;

        for(int i = 0;i<orders.size();++i){
            if(orders[i][2]==0){
                for(auto iter=sellMap.begin();iter!=sellMap.end();++iter){
                     if((orders[i][0]>=(iter->first))&&(iter->second!=0)&&(orders[i][1]!=0)){
                         if(orders[i][1]>=iter->second){
                             orders[i][1] = orders[i][1]-iter->second;
                             iter->second=0;
                         }
                         else{
                             iter->second = iter->second-orders[i][1];
                             orders[i][1] = 0;
                             break;
                         }
                     }
                }
                if(orders[i][1]){
                    buyMap[orders[i][0]]=buyMap[orders[i][0]]+orders[i][1];
                }
            }
            else{
                for(auto iter=buyMap.begin();iter!=buyMap.end();++iter){
                     if((orders[i][0]<=(iter->first))&&(iter->second!=0)&&(orders[i][1]!=0)){
                         if(orders[i][1]>=iter->second){
                             orders[i][1] = orders[i][1]-iter->second;
                             iter->second=0;
                         }
                         else{
                             iter->second = iter->second-orders[i][1];
                             orders[i][1] = 0;
                             break;
                         }
                     }
                }
                if(orders[i][1]){
                    
                    sellMap[orders[i][0]]= sellMap[orders[i][0]]+orders[i][1];
                }
            }
        }
        int result = 0;
        for(auto i = buyMap.begin();i!=buyMap.end();++i){
            i->second = ((i->second)%int(pow(10,9)));
            result = (result+ i->second)%int(pow(10,9)+7);
        }
        for(auto i = sellMap.begin();i!=sellMap.end();++i){
            i->second = ((i->second)%int(pow(10,9)+7));
            result = (result+ i->second)%int(pow(10,9)+7);
        }
        return result;
    }
};

int main(){
    Solution S;
    vector<vector<int>> nums = {{12,16,1},{28,4,0},{19,29,1},{7,10,0},{29,26,0},{4,19,0},{18,10,0},{3,17,1},{19,26,1}};
    cout<<S.getNumberOfBacklogOrders(nums)<<endl;
}